﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

    public partial class admin_DangNhap : System.Web.UI.Page
    {
        TiemPhongDataContext db = new TiemPhongDataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
             {
                 HttpCookie hck = Request.Cookies["ckGhiNhoAD"];
                 if (hck != null)
                 {
                     this.lbThongBao.Text=Server.HtmlEncode(hck.Value);
                     txtTenDN.Text = hck["TenDNAD"];
                     txtMatKhau.Attributes["value"] = MD5.GetMd5Hash(hck["MatKhauAD"]);
                     ckTrangThai.Checked = true;
                 }                 
             }

        }
        
        protected void ibtDangNhap_Click(object sender, ImageClickEventArgs e)
        {
            var data = db.NguoiDungs.Where(c => c.UserName == txtTenDN.Text);
            if (data.Count() == 0)
            {
                lbThongBao.Text = "Tên đăng nhập không tồn tại.";
                txtTenDN.Focus();
            }
            else
            {
                NguoiDung us = data.ToList()[0];
                var ur =  db.UserInRoles.SingleOrDefault(r => r.NguoiDungId==us.NguoiDungId);
                
                if (ur!=null)
                {                    
                    if (us.Password.Trim() != MD5.GetMd5Hash(txtMatKhau.Text).Trim())
                    {
                        lbThongBao.Text = "Mật khẩu không chính xác";
                        txtMatKhau.Focus();
                    }
                    else
                    {
                        lbThongBao.Text = "dang nhap thanh cong";
                        Session["DangNhapAD"] = us.UserName;
                        HttpCookie hck = new HttpCookie("ckGhiNhoAD");
                        if (ckTrangThai.Checked)
                        {
                            hck["TenDNAD"] = txtTenDN.Text;
                            hck["MatKhauAD"] = us.Password;
                            hck.Expires = DateTime.Now.AddDays(30);
                        }
                        else
                            hck.Expires = DateTime.Now;
                        Response.Cookies.Add(hck);
                        Response.Redirect("TrangChu.aspx");
                    }
                    
                }
                else {
                    lbThongBao.Text = "User chưa được cấp quyền";
                    txtMatKhau.Focus();
                }                                 
            }
        }
    }
